#include "Exception.h"
#include <cstdlib>
#include <cstring>
#include <cstdio>

namespace MySTL
{

void Exception::init(const char* message, const char* location, int line)
{
	m_message = strdup(message ? message : "");

	if (NULL != location)
	{
		char buf[100];
		sprintf(buf, ":%d", line);

		m_location = (char*)malloc(strlen(location) + strlen(buf) + 1);
		if (NULL != m_location)
		{
			strcpy(m_location, location);
			strcat(m_location, buf);
		}
	}
	else
	{
		m_location = strdup("");
	}
}

void Exception::init(const char* message, const char* location)
{
	m_message = strdup(message ? message : "");
	m_location = strdup(location ? location : "");
}

Exception::Exception(const char* message)
{
	init(message, NULL);
}

Exception::Exception(const char* location, int line)
{
	init(NULL, location, line);
}

Exception::Exception(const char* message, const char* location, int line)
{
	init(message, location, line);
}

Exception::Exception(const Exception& obj)
{
	init(obj.m_message, obj.m_location);
}

Exception& Exception::operator =(const Exception& obj)
{
	if (this != &obj)
	{
		free(m_message);
		m_message = NULL;
		free(m_location);
		m_location = NULL;

		init(obj.m_message, obj.m_location);
	}

	return *this;
}

const char* Exception::message() const
{
	return m_message;
}

const char* Exception::location() const
{
	return m_location;
}

Exception::~Exception()
{
	free(m_message);
	free(m_location);
}

}